//
//  EpointMailSendViewController.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-1-21.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointMailSendViewController.h"
#import "UIView+Addtions.h"
#import "EPUserField.h"
#import "EpointPersonChooseViewController.h"
#import "EpointStringUtil.h"
//#import "EPBottomPopView.h"
#import "EpointConsts.h"
#import "EPBottomView.h"

#import <MediaPlayer/MediaPlayer.h>
#import "MailInfo.h"
#import "EpointStringUtil.h"
#import "Mail_Send_Task.h"
#import "GTMBase64.h"
#import "KLSwitch.h"

#import "UIImageView+Addtions.h"
#import "MutableSelectViewController.h"
#import "AttachTableViewCell.h"
#import "EpointAttachViewController.h"

#import "SingleFile.h"

#define CellHeight 44
#define UserFieldHeight 23

#define SJRUserFieldTAG (INT_MAX-1)
#define SJRSeparatorLineTAG (INT_MAX-2)

#define CSRUserFieldTAG (INT_MAX-3)
#define CSRSeparatorLineTAG (INT_MAX-4)

#define TitleViewTag (INT_MAX-5)
#define TitleSeparatorLineTAG (INT_MAX-6)
#define TitleFieldTAG (INT_MAX-7)

#define MailSendTaskId 1

#define BtnContainerHeight 33

typedef enum {
    NewType,
    ReplyType,
    ForwordType,
    Write
} SendType;

@interface EpointMailSendViewController () <EPUserFieldDelegate, UITextFieldDelegate, UITextViewDelegate, EPBottomViewDelegate, MutableSelectDataSource, MutableSelectDelegate> {
    NSString *sjrGuids, *csrGuids;
    
    CGFloat sjrHeight, csrHeight;
    SendType sendType;
    
    MailInfo *mailInfo;
}

@property (nonatomic, strong) UIScrollView *contentView;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) EPUserField *sjrUserField;
@property (nonatomic, strong) UIButton *addSJRUserBtn;

@property (nonatomic, strong) EPUserField *csrUserField;
@property (nonatomic, strong) UIButton *addCSRUserBtn;

@property (nonatomic, strong) UITextField *titleField;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIButton *keyboardBtn;

//@property (nonatomic, strong) EPBottomPopView *popView;
@property (nonatomic, strong) EPBottomView *bottomView;

@property (nonatomic, strong) UIButton *attachBtn;
@property (nonatomic, strong) UILabel *attachLabel;

@property (nonatomic, strong) UIView *msgNoticeView;
//@property (nonatomic, strong) UISwitch *msgSwitch;
@property (nonatomic, strong) KLSwitch *msgSwitch;

@property (nonatomic, strong) UITapGestureRecognizer *textViewTap;

@property (nonatomic, strong) UIView *btnContainer;
@property (nonatomic, strong) NSMutableArray *sandboxAttachArray;

@end

@implementation EpointMailSendViewController {
    BOOL isViewDidLoad;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        NSLog(@"INT:%d", INT_MAX);
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (isViewDidLoad == NO) {
        [_textView becomeFirstResponder];
        _textView.inputView = _bottomView;
        [_textView reloadInputViews];
    } else {
        isViewDidLoad = NO;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isViewDidLoad = YES;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
    [self setRightBarButtonItemWithTitle:@"发送" action:@selector(send)];
    self.title = @"新邮件";
    [self checkIsReplyOrForwardMail];
    
    CGRect contentFrame = self.view.bounds;
    contentFrame.size.height = AppHeight - SystemTakeHeight;
    contentFrame.size.width = AppWidth;
    self.contentView = [[UIScrollView alloc] initWithFrame:contentFrame];
    //_contentView.backgroundColor = [UIColor greenColor];
    _contentView.contentSize = CGSizeMake(AppWidth, _contentView.height);
    [self.view addSubview:_contentView];
    
    [self addTopView];
    [self addTextView];
    
    [self addBottomButtonView];
    [self addBottomView];

    [self addKeyboardNotification];
}

- (void)checkIsReplyOrForwardMail {
    sendType = NewType;
    NSString *sendTpye = [initParam objectForKey:@"SendType"];
    if (!sendTpye || [sendTpye isEqualToString:@""]) {
        return;
    }

    mailInfo = [initParam objectForKey:@"MailInfo"];

    if ([sendTpye isEqualToString:@"Reply"]) {
        self.title = @"回复";
        sendType = ReplyType;
        sjrGuids = [NSString stringWithFormat:@"%@;",mailInfo.FromUserGuid];
    }
    else if ([sendTpye isEqualToString:@"write"]) {
        self.title = @"新邮件";
        sendType = Write;
        sjrGuids = mailInfo.ToUserGuidList;
    }
    else {
        self.title = @"转发";
        sendType = ForwordType;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    NSLog(@"memory Warning");
}

#pragma mark - Send

- (void)send {

//    /***
    if (![EpointStringUtil stringIsNotNull:sjrGuids]) {
        [self toastMessage:@"请选择收件人！"];
        return;
    }

    if (![EpointStringUtil stringIsNotNull:_titleField.text]) {
        [self toastMessage:@"标题不能为空！"];
        return;
    }

    [self showMBPHUD];
    // TODO: send
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:sjrGuids forKey:@"ToUserGuidList"];
    
    [params setObject:[EpointStringUtil stringIsNotNull:csrGuids]?csrGuids:@"" forKey:@"ChaoSongUserGuidList"];
    [params setObject:_msgSwitch.on?@"1":@"0" forKey:@"IFNotice"];
    [params setObject:_titleField.text forKey:@"Subject"];
    
    NSString *mailContent = _textView.text;
    if (![EpointStringUtil stringIsNotNull:mailContent]) {
        mailContent = @"";
    }
    if (sendType == ReplyType || sendType == ForwordType) {
        
        NSString *FROMDISPNAME = mailInfo.FROMDISPNAME;
        NSString *SENDTIME = mailInfo.SENDTIME;
        NSString *MailTitle = mailInfo.Subject;
        NSString *mailsendinfo = [NSString stringWithFormat:@"<b>发件人：</b>%@<br/><br/><b>发件时间：</b>%@<br/><br/><b>标题：</b>%@<br/><br/>",FROMDISPNAME,SENDTIME,MailTitle];
        NSString *lastContent = [NSString stringWithFormat:@"%@<br/><br/><hr/><br/><br/>%@%@",mailContent,mailsendinfo,mailInfo.MailContent];
        [params setObject:lastContent forKey:@"MailContent"];
    } else {
        [params setObject:mailContent forKey:@"MailContent"];
    }
//    ***/

    // TODO: what about attach
    NSMutableArray *attachList = [[NSMutableArray alloc] init];
    for (NSDictionary *attachDic in _bottomView.attachArray) {
        NSLog(@"attachDic:%@", attachDic);
        AttachType attachType = [[attachDic objectForKey:@"type"] intValue];
        NSString *name = [attachDic objectForKey:@"title"];
        NSData *fileData;
        NSString *attachGuid = @"";
        switch (attachType) {
            case FILE_TYPE: {
                NSString *fileUrl = [attachDic objectForKey:@"fileUrl"];
                fileData = [[NSFileManager defaultManager] contentsAtPath:fileUrl];
            }
                break;
            case PHOTO_TYPE: {
                UIImage *image = [attachDic objectForKey:@"image"];
                fileData = UIImageJPEGRepresentation(image, RepresentationValue);
            }
                break;
            case VIDEO_TYPE: {
                NSString *videoUrl = [attachDic objectForKey:@"videoUrl"];
                fileData = [[NSFileManager defaultManager] contentsAtPath:videoUrl];
            }
                break;
            case UNRECOG_TYPE: {
                SingleFile *singleFile = [attachDic objectForKey:@"singleFile"];
                attachGuid = singleFile.AttachGuid;
                fileData = nil;
            }
            default:
                break;
        }
        SingleFile *singleFile = [[SingleFile alloc] init];
        singleFile.fileData = fileData;
        singleFile.AttachGuid = attachGuid;
        singleFile.ATTACHFILENAME = name;
        [attachList addObject:singleFile];
//        NSString *fileContent;
//        if (fileData) {
//            fileContent = [GTMBase64 stringByEncodingData:fileData];
//        } else {
//            fileContent = @"";
//        }
//        NSString *fileAttach = [self getAttachWithGuid:attachGuid name:name fileContent:fileContent];
//        [attachList appendString:fileAttach];
    }
    NSString* strOutboxGuid = [self createUUID];
    [params setObject:attachList forKey:@"ATTACHList"];
    [params setObject:strOutboxGuid forKey:@"strOutboxGuid"];
    [self startTask:@"Mail_Send_Task" withParams:params withTaskId:MailSendTaskId];
}
- (NSString *)createUUID
{

    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);

    NSString *uuidStr = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidObject));

    CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuidObject);

    CFRelease(uuidObject);

    return uuidStr;

}


- (NSString *)getAttachWithGuid:(NSString *)guid
                           name:(NSString *)name
                    fileContent:(NSString *)fileContent {

    NSMutableString *mutableString = [[NSMutableString alloc] initWithString:@""];
    [mutableString appendString:@"<ATTACHInfo>"];
    [mutableString appendString:@"<AttachGuid>"];
    [mutableString appendString:guid];
    [mutableString appendString:@"</AttachGuid>"];
    [mutableString appendString:@"<AttachName>"];
    [mutableString appendString:name];
    [mutableString appendString:@"</AttachName>"];
    [mutableString appendString:@"<FileContent>"];
    [mutableString appendString:fileContent];
    [mutableString appendString:@"</FileContent>"];
    [mutableString appendString:@"</ATTACHInfo>"];
    return mutableString;
}

#pragma mark - Subviews

- (void)addTopView {
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, AppWidth, CellHeight*3)];
    //_topView.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.6];
    _topView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:_topView];
    
    // !!!:收件人
    self.sjrUserField = [[EPUserField alloc] initWithFrame:CGRectMake(15, 10, AppWidth-40, UserFieldHeight)];
    _sjrUserField.tag = SJRUserFieldTAG;
    //_sjrUserField.backgroundColor = [UIColor yellowColor];
    _sjrUserField.defaultLabelText = @"收件人 ";
    if ([EpointStringUtil stringIsNotNull:sjrGuids]) {
        
        NSString *toUsrString = mailInfo.ToUserDispNameList;
        //如果是回复 回复的收件人是 发件人的信息
        if (sendType==ReplyType) {
            toUsrString = [NSString stringWithFormat:@"%@;",mailInfo.FROMDISPNAME];
        }
        NSArray *tempArr = [[toUsrString substringToIndex:toUsrString.length-1] componentsSeparatedByString:@";"];
        [_sjrUserField setTags:tempArr];
    } else {
        [_sjrUserField setTags:@[]];
    }
    
    //[_sjrUserField setLabelBackgroundColor:COLOR(134, 190, 216)];
    _sjrUserField.delegate = self;
    [_topView addSubview:_sjrUserField];
    
    //self.addSJRUserBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
    self.addSJRUserBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addSJRUserBtn setImage:[UIImage imageNamed:@"addBtn"] forState:UIControlStateNormal];
    CGRect rect = _addSJRUserBtn.frame;
    rect.size = CGSizeMake(22, 22);
    rect.origin.x = _sjrUserField.right;
    _addSJRUserBtn.frame = rect;
    _addSJRUserBtn.centerY = _sjrUserField.centerY;
    [_addSJRUserBtn addTarget:self action:@selector(addSJRUserBtnPressed) forControlEvents:UIControlEventTouchUpInside];
     NSLog(@"%@", NSStringFromCGRect(_addSJRUserBtn.frame));
    [_topView addSubview:_addSJRUserBtn];
    _addSJRUserBtn.hidden = NO;
    
    UIImageView *sjrSeparatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(15, CellHeight-1, AppWidth-15, 1)];
    sjrSeparatorLine.tag = SJRSeparatorLineTAG;
    sjrSeparatorLine.alpha = 0.5;
    sjrSeparatorLine.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [_topView addSubview:sjrSeparatorLine];
    
    // !!!:抄送人
    self.csrUserField = [[EPUserField alloc] initWithFrame:CGRectMake(15, CellHeight+10, AppWidth-40, UserFieldHeight)];
    _csrUserField.tag = CSRUserFieldTAG;
    //_csrUserField.backgroundColor = [UIColor yellowColor];
    _csrUserField.defaultLabelText = @"抄送人 ";
    [_csrUserField setTags:@[]];
    _csrUserField.delegate = self;
    [_topView addSubview:_csrUserField];
    
//    self.addCSRUserBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
    self.addCSRUserBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addCSRUserBtn setImage:[UIImage imageNamed:@"addBtn"] forState:UIControlStateNormal];
    rect.size = CGSizeMake(22, 22);
    rect.origin.x = _csrUserField.right;
    _addCSRUserBtn.frame = rect;
    _addCSRUserBtn.centerY = _csrUserField.centerY;
    [_addCSRUserBtn addTarget:self action:@selector(addCSRUserBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    NSLog(@"%@", NSStringFromCGRect(_addCSRUserBtn.frame));
    [_topView addSubview:_addCSRUserBtn];
    _addCSRUserBtn.hidden = YES;
    
    UIImageView *csrSeparatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(15, 2*CellHeight-1, AppWidth-15, 1)];
    csrSeparatorLine.tag = CSRSeparatorLineTAG;
    csrSeparatorLine.alpha = 0.5;
    csrSeparatorLine.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [_topView addSubview:csrSeparatorLine];
    
    //[_sjrUserField tapGesture];
    
    
    //标题
    [self addTitleView];
}

- (void)addTitleView {
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 2*CellHeight, AppWidth, CellHeight)];
    titleView.tag = TitleViewTag;
    [_topView addSubview:titleView];
    
    NSString *title = @"主    题 ";
    CGSize textSize = [self getTextSize:title];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, textSize.width, textSize.height)];
    label.text = title;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:FONT_SIZE];
    [titleView addSubview:label];
    
    self.titleField = [[UITextField alloc] initWithFrame:CGRectMake(label.right+2, label.top+1, AppWidth-label.right-2, label.height)];
    _titleField.tag = TitleFieldTAG;
    _titleField.delegate = self;
    //_titleField.backgroundColor = [UIColor yellowColor];
    [titleView addSubview:_titleField];
    
    if (sendType == ReplyType) {
        _titleField.text = [NSString stringWithFormat:@"回复:%@", mailInfo.Subject];
    } else if (sendType == ForwordType){
        _titleField.text = [NSString stringWithFormat:@"转发:%@", mailInfo.Subject];
    }
    
    UIImageView *titleSeparatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(15, CellHeight-1, AppWidth-15, 1)];
    titleSeparatorLine.tag = TitleSeparatorLineTAG;
    titleSeparatorLine.alpha = 0.5;
    titleSeparatorLine.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [titleView addSubview:titleSeparatorLine];
}

- (void)addTextView {
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(5, CellHeight*3, AppWidth-10, AppHeight-CellHeight*3-SystemTakeHeight)];
    _textView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
    _textView.delegate = self;
    _textView.font = [UIFont systemFontOfSize:15];
    [_contentView addSubview:_textView];
}

- (void)addBottomButtonView {
    self.attachBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_attachBtn setImage:[UIImage imageNamed:@"attachBtn_gray"] forState:UIControlStateNormal];
    [_attachBtn setImage:[UIImage imageNamed:@"attachBtn_blue"] forState:UIControlStateSelected];
    [_attachBtn setImage:[UIImage imageNamed:@"attachBtn_blue"] forState:UIControlStateHighlighted];

    [_attachBtn addTarget:self action:@selector(attachBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [_attachBtn addTarget:self action:@selector(attachBtnTouchDown) forControlEvents:UIControlEventTouchDown];
    _attachBtn.frame = CGRectMake(AppWidth-42-5, 0, 42, 25);
    [self.view addSubview:_attachBtn];

    self.attachLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _attachLabel.backgroundColor = [UIColor clearColor];
    _attachLabel.text = @"0";
    _attachLabel.textColor = COLOR(146, 146, 146);  //146
    _attachLabel.font = [UIFont boldSystemFontOfSize:10];
    _attachLabel.frame = CGRectMake(28, 11, 12, 9);
    [_attachBtn addSubview:_attachLabel];
    [_attachLabel setHidden:YES];
    
    
    self.keyboardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_keyboardBtn setImage:[UIImage imageNamed:@"keyboard_blue"] forState:UIControlStateNormal];
    [_keyboardBtn setImage:[UIImage imageNamed:@"keyboard_lightblue"] forState:UIControlStateHighlighted];
    [_keyboardBtn setFrame:CGRectMake(_attachBtn.left-45, AppHeight-SystemTakeHeight-23-5, 42, 23)];
    //    [self setKeyboardBtnHidden:NO];
    [_keyboardBtn addTarget:self action:@selector(keyboardBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    if (!CurrentDeviceISiPad) {
        //[self.view addSubview:_keyboardBtn];
    }

    self.msgNoticeView = [[UIView alloc] initWithFrame:CGRectMake(5, 0, 115, 24)];
    [self.view addSubview:_msgNoticeView];
    
    UILabel *msgLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 62, 21)];
    msgLabel.text = @"短信提醒";
    msgLabel.font = [UIFont systemFontOfSize:FONT_SIZE];
    msgLabel.centerY = _msgNoticeView.height*0.5;
    [_msgNoticeView addSubview:msgLabel];
    
    self.msgSwitch = [[KLSwitch alloc] initWithFrame:CGRectMake(0, 0, 40, 24)];
    _msgSwitch.tintColor = MainTinColor; //COLOR(83, 214, 105);
    _msgSwitch.onTintColor = MainTinColor;
    _msgSwitch.left = msgLabel.right+12;
    _msgSwitch.centerY = _msgNoticeView.height*0.5;
    [_msgNoticeView addSubview:_msgSwitch];
    
    
    self.btnContainer = [[UIView alloc] initWithFrame:CGRectMake(0, AppHeight-SystemTakeHeight-BtnContainerHeight, AppWidth, BtnContainerHeight)];
    [self.view addSubview:_btnContainer];
    _btnContainer.backgroundColor = [UIColor whiteColor];
    UIImageView *line0 = [UIImageView getColorLine:COLOR(248, 248, 249) alpha:1];
    line0.top = 0;
    [_btnContainer addSubview:line0];
    UIImageView *line1 = [UIImageView getColorLine:COLOR(233, 232, 234) alpha:1];
    line1.top = 1;
    [_btnContainer addSubview:line1];
    
    _attachBtn.centerY = 17;
    [_btnContainer addSubview:_attachBtn];
    
    _msgNoticeView.centerY = 17;
    [_btnContainer addSubview:_msgNoticeView];
}

- (void)addBottomView {
    self.bottomView = [[EPBottomView alloc] init];
    _bottomView.delegate = self;
    _bottomView.parentCtrl = self;
    //[self.view addSubview:_bottomView];
    if (sendType == ForwordType) {
        [self getAttachData];
    }
}

- (void)getAttachData {
    NSArray *fileArray =  mailInfo.attachList;
    NSMutableArray *tempAttachArr = [NSMutableArray arrayWithCapacity:fileArray.count];
    for (SingleFile *singleFile in fileArray) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:5];
        [dic setObject:[[NSNumber alloc] initWithInt:UNRECOG_TYPE] forKey:@"type"];
        [dic setObject:@"转发" forKey:@"size"];
        [dic setObject:singleFile.ATTACHFILENAME forKey:@"title"];
        [dic setObject:singleFile forKey:@"singleFile"];
        [tempAttachArr addObject:dic];
    }
    [_bottomView setAttachArray:tempAttachArr];
    [_bottomView reloadAttachView];
}

- (void)hideBottomView {
//    if (!_bottomView.isShow) {
//        [_bottomView showOrHideBottomView:@[_attachBtn, _keyboardBtn, _msgNoticeView]];
//    }
}

- (void)setKeyboardBtnHidden:(BOOL)animated {
//    _keyboardBtn.hidden = animated;
//    _keyboardBtn.alpha = 1.0;
//    if (!animated) {
//        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(fadeKeyboardBtnAlpch:) userInfo:nil repeats:NO];
//    }
}

- (void)fadeKeyboardBtnAlpch:(NSTimer *)timer {
    [timer invalidate];
    timer = nil;
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:1.0f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    _keyboardBtn.alpha = 0.2;
    [UIView commitAnimations];
}

- (void)attachBtnPressed {
    
    [self setAttachBtnSelected:!_attachBtn.selected];
    
    [_titleField resignFirstResponder];
    [_textView resignFirstResponder];
    [_sjrUserField resignFirstResponder];
    [_csrUserField resignFirstResponder];
    
    if (_textView.inputView == nil) {
        [_textView becomeFirstResponder];
        _textView.inputView = _bottomView;
        if (_attachBtn.selected == NO) {
            [self setAttachBtnSelected:YES];
        }
    } else {
        _textView.inputView = nil;
    }
    [_textView reloadInputViews];

    if (_attachBtn.selected) {
        NSLog(@"YES SELECT");
    } else {
        NSLog(@"NO SELECT");
        //TODO: hidein
        //[self performSelector:@selector(delay) withObject:nil afterDelay:0.3];
        //[self delay];
    }
    //[_bottomView showOrHideBottomView:@[_attachBtn, _keyboardBtn, _msgNoticeView]];
    
}

- (void)setAttachBtnSelected:(BOOL)selected {
    _attachBtn.selected = selected;
    [self updateAttachBtnAndLabel];
}

- (void)updateAttachBtnAndLabel {
    if (_attachBtn.selected) {
        _attachLabel.textColor = [UIColor whiteColor];
    } else {
        _attachLabel.textColor = COLOR(47, 145, 244);
        if ([_attachLabel.text isEqualToString:@"0"]) {
            _attachLabel.hidden = YES;
            [_attachBtn setImage:[UIImage imageNamed:@"attachBtn_gray"] forState:UIControlStateNormal];
        } else {
            _attachLabel.hidden = NO;
            [_attachBtn setImage:[UIImage imageNamed:@"attachBtn_blue_h"] forState:UIControlStateNormal];
        }
    }
}

- (void)delay {
    [UIView beginAnimations:@"moveContentView" context:nil];
    [UIView setAnimationDuration:0.25];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    _contentView.height = AppHeight - SystemTakeHeight;
    _keyboardBtn.top = AppHeight-SystemTakeHeight-23-5;
    _msgNoticeView.top = AppHeight-SystemTakeHeight-24-5;
    _attachBtn.top = AppHeight-SystemTakeHeight-25-5;
    [UIView commitAnimations];
}

- (void)attachBtnTouchDown {
    _attachLabel.textColor = [UIColor whiteColor];
}

- (void)keyboardBtnPressed {
    _keyboardBtn.alpha = 1.0;
    [_textView resignFirstResponder];
    [self setKeyboardBtnHidden:YES];
}

- (void)addSJRUserBtnPressed {
    // TODO:添加收件人
    [self hideBottomView];
    NSString *names = [NSString stringWithFormat:@"%@;", [_sjrUserField.textArray componentsJoinedByString:@";"]];
    [EpointPersonChooseViewController pushChoosePerson:self WithTag:@"sjr" AndNames:names AndGuids:sjrGuids];
}

- (void)addCSRUserBtnPressed {
    // TODO:添加抄送人
    [self hideBottomView];
    NSString *names = [NSString stringWithFormat:@"%@;", [_csrUserField.textArray componentsJoinedByString:@";"]];
    [EpointPersonChooseViewController pushChoosePerson:self WithTag:@"csr" AndNames:names AndGuids:csrGuids];
}

- (void)removeKeyboardNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)addKeyboardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if (_keyboardBtn.hidden) {
        return;
    }
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [self moveContentViewWithKeyboardHeght:0.0f withDuration:animationDuration];
}

- (void)keyboardWillChange:(NSNotification *)notification {
    if (_keyboardBtn.hidden) {
        return;
    }
    NSDictionary *userInfo = [notification userInfo];
    
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    CGFloat keyHeight;
    if (IsiOS8Over) {
        keyHeight=keyboardRect.size.height;
    }else{
        keyHeight=(CurrentDeviceISiPad ? keyboardRect.size.width : keyboardRect.size.height);
    }
    [self moveContentViewWithKeyboardHeght:keyHeight withDuration:animationDuration];
}

- (void)moveContentViewWithKeyboardHeght:(CGFloat)height
                            withDuration:(NSTimeInterval)animationDuration {

    CGFloat newHeight = AppHeight - SystemTakeHeight - height;
    if (_contentView.height == newHeight) {
        return;
    }

    [UIView beginAnimations:@"moveContentView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    _contentView.height = AppHeight - SystemTakeHeight - height - BtnContainerHeight;
    NSLog(@"height:%f", height);
    if (height == 0) {
        
        NSLog(@"%@", _textView.inputView != nil ?@"1111":@"22222");
        NSLog(@"%@", _textView.isFirstResponder ? @"is first" :@"not first");
        if (_textView.inputView == nil && _textView.isFirstResponder) {
//            _keyboardBtn.top = AppHeight-SystemTakeHeight-23-5 - BottomViewHeight;
//            _msgNoticeView.top = AppHeight-SystemTakeHeight-24-5 - BottomViewHeight;
//            _attachBtn.top = AppHeight-SystemTakeHeight-25-5 - BottomViewHeight;
            _btnContainer.top = AppHeight-SystemTakeHeight-BtnContainerHeight - BottomViewHeight;
        } else {
//            _keyboardBtn.top = AppHeight-SystemTakeHeight-23-5;
//            _msgNoticeView.top = AppHeight-SystemTakeHeight-24-5;
//            _attachBtn.top = AppHeight-SystemTakeHeight-25-5;
            _btnContainer.top = AppHeight-SystemTakeHeight-BtnContainerHeight;
            if (_textView.isFirstResponder == NO) {
                [self setAttachBtnSelected:NO];
            }
        }
    } else {
//        _keyboardBtn.top = AppHeight-SystemTakeHeight-23-5 - height;
//        _msgNoticeView.top = AppHeight-SystemTakeHeight-24-5 - height;
//        _attachBtn.top = AppHeight-SystemTakeHeight-25-5 - height;
        _btnContainer.top = AppHeight-SystemTakeHeight-BtnContainerHeight - height;
    }
    [UIView commitAnimations];
}

#pragma mark - update subview frame

- (void)updateSubViewsFrame {
    
    BOOL cellHeightChanged = NO;
    
    CGFloat sjrFieldHeigjt = [_sjrUserField getUserFieldHeight];
    if (sjrHeight != sjrFieldHeigjt) {
        cellHeightChanged = YES;
        [self updateSJRView];
    }
    
    CGFloat csrFieldHeigjt = [_csrUserField getUserFieldHeight];
    if (csrHeight != csrFieldHeigjt) {
        cellHeightChanged = YES;
        [self updateCSRView];
    }
    
    if (cellHeightChanged) {
        UIImageView *csrSeparatorLine = (UIImageView *)[self.view viewWithTag:CSRSeparatorLineTAG];
        
        UIView *titleView = [_topView viewWithTag:TitleViewTag];
        titleView.top = csrSeparatorLine.bottom;
        _topView.height = titleView.bottom;
        
        _textView.top = _topView.bottom;
//        _keyboardBtn.top = _textView.top + 10;
        _contentView.contentSize = CGSizeMake(AppWidth, _textView.bottom);
    }
}

- (void)updateSJRView {
    CGFloat sjrFieldHeigjt = [_sjrUserField getUserFieldHeight];
    CGFloat sjrViewHeight = CellHeight - UserFieldHeight + sjrFieldHeigjt;
    
    CGRect sjrFieldFrame = _sjrUserField.frame;
    sjrFieldFrame.size.height = sjrFieldHeigjt;
    _sjrUserField.frame = sjrFieldFrame;
    
    UIImageView *sjrSeparatorLine = (UIImageView *)[self.view viewWithTag:SJRSeparatorLineTAG];
    CGRect sjrRect = sjrSeparatorLine.frame;
    sjrRect.origin.y = sjrViewHeight - 1;
    sjrSeparatorLine.frame = sjrRect;
    
    // 抄送人
    CGRect csrFieldFrame = _csrUserField.frame;
    csrFieldFrame.origin.y = sjrViewHeight + 10;
    _csrUserField.frame = csrFieldFrame;
    
    CGRect csrBtnrect = _addCSRUserBtn.frame;
    csrBtnrect.origin.x = _csrUserField.right;
    csrBtnrect.origin.y = _csrUserField.top+0.5;
    _addCSRUserBtn.frame = csrBtnrect;
    
}

- (void)updateCSRView {
    CGFloat sjrFieldHeigjt = [_sjrUserField getUserFieldHeight];
    CGFloat sjrViewHeight = CellHeight - UserFieldHeight + sjrFieldHeigjt;
    
    CGFloat csrFieldHeigjt = [_csrUserField getUserFieldHeight];
    CGFloat csrViewHeight = CellHeight - UserFieldHeight + csrFieldHeigjt;
    
    CGRect csrFieldFrame = _csrUserField.frame;
    csrFieldFrame.size.height = csrFieldHeigjt;
    _csrUserField.frame = csrFieldFrame;
    
    UIImageView *csrSeparatorLine = (UIImageView *)[self.view viewWithTag:CSRSeparatorLineTAG];
    CGRect csrRect = csrSeparatorLine.frame;
    csrRect.origin.y = sjrViewHeight + csrViewHeight - 1;
    csrSeparatorLine.frame = csrRect;
}

#pragma mark - EPUserFieldDelegate

- (void)epuserfield:(EPUserField *)userfield selectedIndex:(int)index {
    NSLog(@"selected:%d", index);
}

- (void)epuserfield:(EPUserField *)userfield removedIndex:(int)index {
    NSLog(@"removed:%d", index);
    if (userfield.tag == SJRUserFieldTAG) {
        sjrGuids = [self removeStringItem:sjrGuids atIndex:index];
    } else if (userfield.tag == CSRUserFieldTAG) {
        csrGuids = [self removeStringItem:csrGuids atIndex:index];
    }
    [self updateSubViewsFrame];
}

- (void)epuserfieldOnFoucs:(EPUserField *)userfield {
    if (userfield.tag == SJRUserFieldTAG) {
        _addSJRUserBtn.hidden = NO;
        _addCSRUserBtn.hidden = YES;
    } else if (userfield.tag == CSRUserFieldTAG) {
        _addCSRUserBtn.hidden = NO;
        _addSJRUserBtn.hidden = YES;
    }
    [self hideBottomView];
}

- (void)epuserfieldOnBlur:(EPUserField *)userfield {
//    if (userfield.tag == SJRUserFieldTAG) {
//        _addSJRUserBtn.hidden = YES;
//    } else if (userfield.tag == CSRUserFieldTAG) {
//        _addCSRUserBtn.hidden = YES;
//    }
}

#pragma mark - people choose call back

-(void)epointPerson:(NSString *)controlTag chooseData:(NSMutableArray *)data
{
    NSArray *arr =[EpointPersonChooseViewController getChoosedArray:data];
    if ([controlTag isEqualToString:@"sjr"]) {
        NSString *tempStr = [arr objectAtIndex:0];
        if ([EpointStringUtil stringIsNotNull:tempStr]) {
            NSArray *tempArr = [[tempStr substringToIndex:tempStr.length-1] componentsSeparatedByString:@";"];
            [_sjrUserField setTags:tempArr];
        } else {
            [_sjrUserField setTags:nil];
        }
        [_sjrUserField tapGesture];
        sjrGuids = [arr objectAtIndex:1];
    }
    else if ([controlTag isEqualToString:@"csr"])
    {
        NSString *tempStr = [arr objectAtIndex:0];
        if ([EpointStringUtil stringIsNotNull:tempStr]) {
            NSArray *tempArr = [[tempStr substringToIndex:tempStr.length-1] componentsSeparatedByString:@";"];
            [_csrUserField setTags:tempArr];
        } else {
            [_csrUserField setTags:nil];
        }
        [_csrUserField tapGesture];
        csrGuids = [arr objectAtIndex:1];
    }

    [self updateSubViewsFrame];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField.tag == TitleFieldTAG) {
        _addCSRUserBtn.hidden = YES;
        _addSJRUserBtn.hidden = YES;
    }
    [self hideBottomView];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
//    [self setKeyboardBtnHidden:NO];
    if (_textView.inputView) {
        _textView.inputView = nil;
    }
    _bottomView.isShow = YES;
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    _addCSRUserBtn.hidden = YES;
    _addSJRUserBtn.hidden = YES;
    [self hideBottomView];
}

#pragma mark - Some Deal Function

- (NSString *)removeStringItem:(NSString *)string atIndex:(int)index {
    
    NSArray *tempArr = [[string substringToIndex:string.length-1] componentsSeparatedByString:@";"];
    NSMutableArray *tempMutableArr = [[NSMutableArray alloc] initWithArray:tempArr];
    [tempMutableArr removeObjectAtIndex:index];
    NSString *tempStr = [NSString stringWithFormat:@"%@;", [tempMutableArr componentsJoinedByString:@";"]];
    return tempStr;
}

- (CGSize)getTextSize:(NSString *)text {
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:CGSizeMake(AppWidth, 1500) lineBreakMode:NSLineBreakByWordWrapping];
    textSize.height += VERTICAL_PADDING*2;
    return textSize;
}

#pragma mark - EPBottomViewDelegate

- (void)shouldShowFileMutableSelectCtrl:(NSMutableArray *)selectedIndexs {
    
    if (self.sandboxAttachArray == nil) {
        self.sandboxAttachArray = [EpointAttachViewController getAllAttachArray];
    }

    MutableSelectViewController *mutableSelectCtrl = [[MutableSelectViewController alloc] initWithParams:nil];
    [mutableSelectCtrl view];
    mutableSelectCtrl.delegate = self;
    mutableSelectCtrl.datasource = self;
    mutableSelectCtrl.selectedIndexArray = selectedIndexs;
    [mutableSelectCtrl reloadTableView];
    [self.navigationController pushViewController:mutableSelectCtrl animated:YES];
}

- (void)attachNumberChanged:(int)count {
    self.attachLabel.text = [NSString stringWithFormat:@"%d", count];
    if (count > 0) {
        [self updateAttachBtnAndLabel];
    }
}

- (void)openAttach {
    [_textView resignFirstResponder];
    _textView.inputView = nil;
}

#pragma mark - MutableSelectDataSource

- (UITableViewCell *)mutableSelectCtrl:(MutableSelectViewController *)mutableSelectCtrl
                      cellForIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    AttachTableViewCell *cell = [[AttachTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    cell.attachInfo = [_sandboxAttachArray objectAtIndex:indexPath.row];
    return cell;
}

- (NSInteger)mutableSelectCtrl:(MutableSelectViewController *)mutableSelectCtrl
         numberOfRowsInSection:(NSInteger)section {
    return _sandboxAttachArray.count;
}

#pragma mark - MutableSelectDelegate

- (void)mutableSelectCtrlCancel:(MutableSelectViewController *)mutableSelectCtrl {
    NSLog(@"cancel");
}

- (CGFloat)mutableSelectCtrl:(MutableSelectViewController *)mutableSelectCtrl
     heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0;
}

- (void)dismissFromParentView:(MutableSelectViewController *)mutableSelectCtrl {
    NSLog(@"dismiss ...");
}

- (void)backToLastView:(NSMutableArray *)selectedIndexs {
    [_bottomView okButtonPressed:selectedIndexs];
}

#pragma mark -

- (void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj {
    [self hideMBPHUD];
    
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        [self toastMessage:[arr objectAtIndex:1]];
        return;
    }
    
    if (taskId == MailSendTaskId) {
        [self toastMessage:[arr lastObject]];
        //处理ipad发送成功后，关闭发送界面 edit by wangzhigang at 2014-07-03 周四 15:06
        if (CurrentDeviceISiPad) {
            NSArray* arr=self.navigationController.viewControllers;
            NSLog(@"count=%i",arr.count);
            [self.navigationController popViewControllerAnimated:YES];
            EpointPhoneViewController* backVc =[arr objectAtIndex:0];
            [backVc popBack];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

@end
